package org.darkforest.merchant.controller;

import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.darkforest.common.services.DeliverService;
import org.darkforest.common.services.ExpressService;
import org.darkforest.common.services.StoreExtendsService;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.util.JacksonsUtil;
import org.darkforest.dao.mapper.DAddressMapper;
import org.darkforest.dao.mapper.GoodsMapper;
import org.darkforest.dao.mapper.OrderBillMapper;
import org.darkforest.dao.mapper.OrderGiftCodeMapper;
import org.darkforest.dao.mapper.StoreMapper;
import org.darkforest.enums.AjaxMsgTypeEnum;
import org.darkforest.enums.OrderStatusEnum;
import org.darkforest.merchant.service.OrderService;
import org.darkforest.merchant.service.WXMessageService;
import org.darkforest.merchant.utils.JSONUtils;
import org.darkforest.model.*;
import org.darkforest.ucenter.auth.AuthPassport;
import org.darkforest.vo.AjaxReturnData;
import org.darkforest.vo.StoreSellerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;

/**
 * Created by chenyu on 15/1/30.
 * 订单物流相关控制类
 */
@Controller
@RequestMapping(value="/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private DeliverService deliverService;

    @Value("#{configProperties['pcweb.goodsDetail']}")
    private String goodsDetailPath;

    @Autowired
    private DAddressMapper dAddressMapper;

    @Autowired
    private StoreExtendsService storeExtendsService;
    @Autowired
    private OrderGiftCodeMapper orderGiftCodeMapper;

    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private ExpressService expressService;

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private OrderBillMapper orderBillMapper;

    /**
     * 订单列表
     * @param request
     * @return
     */
    @RequestMapping(value = "orderList")
    public ModelAndView orderList(HttpServletRequest request,OrderSearchBean page) {
        if (page.getOrderState() == null || "".equals(page.getOrderState())) {
            page.setOrderState("-1");
        }

        Integer storeId = ((StoreSellerVo) request.getSession().getAttribute("sellerInfo")).getStoreId();
        page.setStoreId(storeId);
        page.setOrderByColume("add_time");
        page.setOrderByType("desc");
        orderService.selectListByCondition(page);
        List<OrderVo> list = page.getResultList();
        for(OrderVo orderVo:list){
            OrderCommonVo commonVo = orderVo.getCommon();
            if(!"".equals(commonVo.getReciverInfo())&&commonVo.getReciverInfo()!=null) {
                Address address = JacksonsUtil.newInstance().json2Obj(commonVo.getReciverInfo(), Address.class);
                commonVo.setAddress(address);
            }
        }
        return new ModelAndView("order/orderList", "page", page);
    }


    @RequestMapping(value = "orderDetail")
    public ModelAndView orderDetail(int orderId) {
        OrderVo orderVo= orderService.selectById(orderId);
        OrderCommonVo commonVo = orderVo.getCommon();
        if(!"".equals(commonVo.getReciverInfo())&&commonVo.getReciverInfo()!=null) {
            Address address = JacksonsUtil.newInstance().json2Obj(commonVo.getReciverInfo(), Address.class);
            commonVo.setAddress(address);
        }
        OrderGiftCode record = new OrderGiftCode();
        record.setGenerateOrderId(Integer.toString(orderId));
        ModelAndView res = new ModelAndView("order/orderDetail","orderVo",orderVo);
        List<OrderGiftCode> list = orderGiftCodeMapper.selectByCondition(record);
        res.addObject("orderGiftCodes",list);
        if(commonVo.getInvoiceInfo()!=null&&!commonVo.getInvoiceInfo().equals("")){
            Invoice  invoice  =com.alibaba.fastjson.JSONObject.parseObject(commonVo.getInvoiceInfo(),Invoice.class);
            res.addObject("invoice",invoice);
        }
        Integer expressId = commonVo.getShippingExpressId();
        if (expressId != null) {
            Express express = expressService.selectByPrimaryKey(expressId);
            res.addObject("express", express);
        }

        // 结算信息的取得
        if (Integer.valueOf(orderVo.getOrderState()) == OrderStatusEnum.SETTLED.getValue()) {
            // 销售价、成本价、支付价、抽取的佣金的取得
            BigDecimal goodsPrice = new BigDecimal(0);
            BigDecimal costPrice = new BigDecimal(0);
            BigDecimal payPrice = new BigDecimal(0);
            BigDecimal brokerage = new BigDecimal(0);

            for (OrderGoods orderGoods : orderVo.getGoods()) {
                Goods goods = goodsMapper.selectByPrimaryKey(orderGoods.getGoodsId());
                goodsPrice =  goodsPrice.add(goods.getGoodsPrice());
                costPrice = costPrice.add(goods.getCostPrice());
                payPrice = payPrice.add(orderGoods.getGoodsPayPrice());
                //佣金类型是进销价比例
                if (goods.getCommissionType() == 1) {
                    brokerage = brokerage.add(goods.getGoodsPrice().subtract(goods.getCostPrice()).multiply(new BigDecimal(goods.getCommissionRate()).divide(new BigDecimal(100))).multiply(new BigDecimal(orderGoods.getGoodsNum())));
                } else if (goods.getCommissionType() == 2) { //按照售价比例
                    brokerage = brokerage.add(goods.getGoodsPrice().multiply(new BigDecimal(goods.getCommissionRate()).divide(new BigDecimal(100))).multiply(new BigDecimal(orderGoods.getGoodsNum())));

                } else {
                    //商品佣金类型错误
                }
            }
            goodsPrice = goodsPrice.setScale(2, RoundingMode.HALF_UP);
            res.addObject("goodsPrice", goodsPrice);
            costPrice = costPrice.setScale(2, RoundingMode.HALF_UP);
            res.addObject("costPrice", costPrice);
            payPrice = payPrice.setScale(2, RoundingMode.HALF_UP);
            res.addObject("payPrice", payPrice);
            brokerage = brokerage.setScale(2, RoundingMode.HALF_UP);
            res.addObject("brokerage", brokerage);

            // 结算时间的取得
            OrderBill orderBill = new OrderBill();
            orderBill.setObStoreId(orderVo.getStoreId());
            String finnshedTime = orderVo.getFinnshedTimeStr();  // %Y-%m-%d %H:%i:%s
            // %Y-%m-%d %H:%i:%s  -->> 201805
            String[] yearMonth = finnshedTime.split("-");
            String yearMonthStr = yearMonth[0]+yearMonth[1];
            orderBill.setOsMonth(Integer.valueOf(yearMonthStr));

            List<OrderBill> billList = orderBillMapper.selectByCondition(orderBill);
            if (billList != null && billList.size() > 0) {
                // 满足以上条件的数据最多只会有一条
                orderBill = billList.get(0);
                res.addObject("orderBill", orderBill);
            }
        }

        return res;
    }


    @RequestMapping(value = "print")
    public ModelAndView print(int orderId) {
        OrderVo orderVo= orderService.selectById(orderId);
        OrderCommonVo commonVo = orderVo.getCommon();
        if(!"".equals(commonVo.getReciverInfo())&&commonVo.getReciverInfo()!=null) {
            Address address = JacksonsUtil.newInstance().json2Obj(commonVo.getReciverInfo(), Address.class);
            commonVo.setAddress(address);
        }

//        List<Store> storeList = deliverService.selectAllStore();
        Store store = storeMapper.selectStoreByPrimaryKey(orderVo.getStoreId());

        ModelAndView modelAndView = new ModelAndView("order/print","orderVo",orderVo);
        modelAndView.addObject("store",store);
        return modelAndView;
    }

        @RequestMapping(value = "orderCancel")
        public ModelAndView orderCancel(int orderId) {
            OrderVo orderVo= orderService.selectById(orderId);
            return new ModelAndView("order/orderCancel","orderVo",orderVo);
        }


        @RequestMapping(value = "doCancel")
        public ModelAndView doCancel(Order order) {
            order.setFinnshedTime(DateUtil.unixTimeStampInt().intValue());
            orderService.updateByPrimaryKeySelective(order);
            return new ModelAndView("order/orderCancel");
        }

    @RequestMapping(value = "orderDel")
    public ModelAndView orderDel(Order order,int start,String pstate) {
        order.setFinnshedTime(DateUtil.unixTimeStampInt().intValue());
        orderService.orderDel(order);
        return new ModelAndView("redirect:/order/orderList?start="+start+"&orderState="+pstate);
    }



//发货列表
    @RequestMapping(value = "deliverList")
    public ModelAndView deliverList(OrderSearchBean page,HttpServletRequest request) {
        Integer storeId = ((StoreSellerVo) request.getSession().getAttribute("sellerInfo")).getStoreId();
        page.setStoreId(storeId);
        if("".equals(page.getOrderState())||page.getOrderState()==null){
            page.setOrderState("20");
        }
        page.setPostType(1);
        orderService.selectListByCondition(page);
        List<OrderVo> list = page.getResultList();
        for(OrderVo orderVo:list){
            OrderCommonVo commonVo = orderVo.getCommon();
            if(!"".equals(commonVo.getReciverInfo())&&commonVo.getReciverInfo()!=null) {
                Address address = JacksonsUtil.newInstance().json2Obj(commonVo.getReciverInfo(), Address.class);
                commonVo.setAddress(address);
            }
        }
        return new ModelAndView("order/deliverList", "page", page);
    }



    //发货列表
    @AuthPassport
    @RequestMapping(value = "deliverSet")
    public ModelAndView deliverSet(int orderId,HttpSession session) {
        StoreSellerVo sellerVo = (StoreSellerVo)session.getAttribute("sellerInfo");
        OrderVo orderVo= orderService.selectById(orderId);
        OrderCommonVo commonVo = orderVo.getCommon();
        if(!"".equals(commonVo.getReciverInfo())&&commonVo.getReciverInfo()!=null) {
            Address address = JacksonsUtil.newInstance().json2Obj(commonVo.getReciverInfo(), Address.class);
            commonVo.setAddress(address);
        }
        List companyList = deliverService.getStoreExpress(sellerVo.getStoreId());
        ModelAndView modelAndView = new ModelAndView("order/deliverSet","orderVo",orderVo);
//        modelAndView.addObject("dAddress", );
        if(commonVo.getDaddressId()!=null)
             orderVo.setDaddress(dAddressMapper.selectByPrimaryKey(commonVo.getDaddressId()));
        else
            orderVo.setDaddress(dAddressMapper.selectByStoreId(sellerVo.getStoreId()));//直接获取默认地址
        modelAndView.addObject("companyList",companyList);
        return modelAndView;
    }

    //打印运单模板

    @RequestMapping(value = "printDeliver")
    public ModelAndView printDeliver(int orderId,int expressId,HttpSession session) {
        Integer storeId = ((StoreSellerVo)session.getAttribute("sellerInfo")).getStoreId();
        OrderVo orderVo= orderService.selectById(orderId);
        OrderCommonVo commonVo = orderVo.getCommon();
        if(!"".equals(commonVo.getReciverInfo())&&commonVo.getReciverInfo()!=null) {
            Address address = JacksonsUtil.newInstance().json2Obj(commonVo.getReciverInfo(), Address.class);
            commonVo.setAddress(address);
        }
        //获取发货地址
        orderVo.setDaddress(dAddressMapper.selectByStoreId(storeId));
        StoreExtend storeExtend=storeExtendsService.selectByPrimaryKey(storeId);
        String expressIds = null;
        if(storeExtend != null && StringUtils.isNotEmpty(storeExtend.getExpress())) {
            expressIds = storeExtend.getExpress();
        }
        List<Express> companyList =null;
        if(expressIds !=null){
            String[] list = expressIds.split(",");
            if(list.length !=0){
                List nList = Arrays.asList(list);
                companyList = deliverService.selectAllOfExpress(nList);
            }
        }
//        List<Express> companyList = deliverService.selectAllUsedExpress();
        Express defaultExpress = null;

        if(expressId==0){
            if(companyList!=null){
                for(Express express:companyList){
                    Waybill wayBill = express.getWaybill();
                    if(wayBill!=null&&wayBill.getWaybillUsable()){
                        defaultExpress = express;
                        break;
                    }
                }
            }
        }else{
            defaultExpress = deliverService.selectByExpressId(expressId);
        }

        Waybill bill = null;
        if(defaultExpress!=null&&defaultExpress.getWaybill()!=null) {
            bill = defaultExpress.getWaybill();
            String data = bill.getWaybillData();
            WayBillData billData = null;
            if (data != null && !"".equals(data)) {
                JSONObject jsonObject = JSONUtils.toJSONObject(data);
                billData = JSONUtils.toBean(jsonObject, WayBillData.class);
                bill.setBillData(billData);
            }
        }
        ModelAndView modelAndView = new ModelAndView("order/printDeliver","orderVo",orderVo);
        modelAndView.addObject("companyList",companyList);
        modelAndView.addObject("bill",bill);
        modelAndView.addObject("defaultExpress",defaultExpress);
        return modelAndView;
    }

    //修改收货人信息。
    //发货列表
    @RequestMapping(value = "editDeliverUserInf")
    public ModelAndView editDeliverUserInf(int orderId) {
        OrderVo orderVo= orderService.selectById(orderId);
        OrderCommonVo commonVo = orderVo.getCommon();
        if(!"".equals(commonVo.getReciverInfo())&&commonVo.getReciverInfo()!=null) {
            Address address = JacksonsUtil.newInstance().json2Obj(commonVo.getReciverInfo(), Address.class);
            commonVo.setAddress(address);
        }

        return new ModelAndView("order/editDeliverUserInfo","orderVo",orderVo);
    }

    //修改收货人信息。
    //发货列表
    @RequestMapping(value = "doEditDeliverUserInfo")
    public ModelAndView doEditDeliverUserInfo(int orderId, Address address) {
        OrderCommon orderCommon= orderService.getOrderCommonById(orderId);
        Address oldAddress = JacksonsUtil.newInstance().json2Obj(orderCommon.getReciverInfo(), Address.class);
        oldAddress.setAddress(address.getAddress());
        oldAddress.setMobPhone(address.getMobPhone());
        oldAddress.setAreaInfo(address.getAreaInfo());
        oldAddress.setTelPhone(address.getTelPhone());
        oldAddress.setTrueName(address.getTrueName());
        String recInfo = JacksonsUtil.newInstance().readAsString(oldAddress);
        orderCommon.setReciverInfo(recInfo);
        orderCommon.setReciverName(address.getTrueName());
        orderCommon.setDeliverExplain(address.getDeliverExplain());
        orderService.updateOrderCommon(orderCommon);
        return new ModelAndView("redirect:/order/deliverSet?orderId="+orderId);
    }

/*    @RequestMapping(value = "selectCompany")
    public ModelAndView  selectCompany(){
        List addressList = orderService.selectByMember(1);
        return new ModelAndView("order/selectCompany","addressList",addressList);
    }*/

    @RequestMapping(value = "selectAddress")
    public ModelAndView  doSelectCompany(int orderId,HttpSession session){
        StoreSellerVo sellerVo = (StoreSellerVo)session.getAttribute("sellerInfo");
        List addressList = deliverService.selectAddress(sellerVo.getStoreId());
        ModelAndView modelAndView =  new ModelAndView("order/selectAddress","addressList",addressList);
        modelAndView.addObject("orderId", orderId);
        return  modelAndView;
    }

    @RequestMapping(value = "doSelectCompany")
    public void  doSelectCompany(HttpServletResponse response ,OrderCommon orderCommon) throws IOException {
        orderService.updateOrderCommon(orderCommon);
        JSONObject json = new JSONObject();
        json.put("result", "true");
        PrintWriter out = response.getWriter();
        out.write(json.toString());
    }


    //当填写完发货号后  点击确定。
    @RequestMapping(value = "updateShippingCode")
    public ModelAndView  updateShippingCode(OrderCommon common, Order order){
       /* System.out.println(orderId + "   " + shippingCode + "  " + shippingId);
        OrderCommon common = new OrderCommon();
        common.setOrderId(orderId);
        common.setShippingExpressId(shippingId);*/
//        orderService.updateOrderCommon(common);

        /*Order order = new Order();
        order.setOrderId(orderId);
        order.setShippingCode(shippingCode);
        order.setOrderState("30");*/
//        orderService.updateByPrimaryKeySelective(order);
//        wXMessageService.setWXMessage(order.getOrderId());

        orderService. deliverGoods(common, order);

        return new ModelAndView("redirect:/order/deliverList");
    }


    //当填写完发货号后  点击确定。
    @RequestMapping(value = "updateState")
    public ModelAndView  updateState(Order order,OrderCommon common){
        common.setShippingTime(DateUtil.unixTimeStampInt().intValue());
        orderService. deliverGoods(common, order);
            return new ModelAndView("redirect:/order/deliverList");

    }

    /**商品批量删除（修改状态）
     * @return
     * @throws Exception
     */
    @RequestMapping(value="deleteOrderBatch")
    public @ResponseBody AjaxReturnData deleteOrderBatch(String[] orderIds){
        AjaxReturnData data = new AjaxReturnData();
        data.setUrl("order/orderList");
        data.setMessage("订单删除成功");
        data.setType(AjaxMsgTypeEnum.SUCC.getText());
        orderService.deleteOrderBatch(orderIds);
        return data;
    }

}
